package com.zz.tijian.filter;

import com.zz.tijian.constants.HeaderConstants;
import com.zz.tijian.entity.req.CurrentUserInfo;
import com.zz.tijian.utils.JwtTool;
import com.zz.tijian.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author itcast
 */
@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

    private final JwtTool jwtTool =new JwtTool();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 尝试获取头信息中的用户信息，还没完善是否登录校验
        String token = request.getHeader(HeaderConstants.USER_INFO);
        if (token == null) {
            return true;
        }
        try {
            // 解析JWT
            CurrentUserInfo currentUserInfo = jwtTool.parseToken(token);
            if (currentUserInfo != null) {
                // 保存用户信息到上下文
                UserContext.set(currentUserInfo);
            }
            return true;
        } catch (Exception e) {
            log.error("解析JWT token失败，原因：{}", e.getMessage());
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户信息
        UserContext.clear();
    }
}
